<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use GuzzleHttp\Client;
use think\Env;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    public function index1()
    {
        return $this->view->fetch();
    }

    function callChatGPT($messages, $apiKey) {
        $url = 'https://api.openai.com/v1/chat/completions'; // 使用正确的API端点
        $data = [
            'model' => 'gpt-4', // 使用GPT-4模型
            'messages' => $messages,
            'max_tokens' => 1500, // 设置响应的最大token数
            'temperature' => 0.7, // 控制生成文本的随机性
        ];

        $options = [
            'http' => [
                'header' => "Content-Type: application/json\r\n" .
                    "Authorization: Bearer $apiKey\r\n",
                'method' => 'POST',
                'content' => json_encode($data),
            ],
        ];

        $context = stream_context_create($options);
        $response = file_get_contents($url, false, $context);

        if ($response === FALSE) {
            die('Error occurred');
        }
        if (isset($http_response_header[0]) && str_contains($http_response_header[0], '200')) {
            $responseData = json_decode($response, true);
            return $responseData['choices'][0]['message']['content'] ?? 'Error: No content found in response.';
        } else {
            return 'Error: ' . $http_response_header[0];
        }

    }

    function generateImage($prompt, $apiKey) {
        $url = 'https://api.openai.com/v1/images/generations';
        $data = [
            'prompt' => $prompt,
            'n' => 1, // 生成图像的数量
            'size' => '580x249' // 图像的尺寸
        ];

        $options = [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                "Content-Type: application/json",
                "Authorization: Bearer $apiKey"
            ],
            CURLOPT_POSTFIELDS => json_encode($data)
        ];

        $ch = curl_init();
        curl_setopt_array($ch, $options);
        $response = curl_exec($ch);

        if(curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }

        curl_close($ch);

        return json_decode($response, true);
    }

    function downloadImage($url, $saveTo) {
        $ch = curl_init($url);
        $fp = fopen($saveTo, 'wb');

        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);

        curl_exec($ch);

        if(curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }

        curl_close($ch);
        fclose($fp);
    }

    public function index(): array
    {
        $apiKey = Env::get('key.apikey'); // 替换为您的实际API密钥

        $content = $this->request->get('content','中国陕西眉县猕猴桃');
        $messages = [
            ['role' => 'system', 'content' => 'You are a helpful assistant.'],
            ['role' => 'user', 'content' => $content]
        ];

        $text = $this->callChatGPT($messages, $apiKey);

        $response = $this->generateImage($text, $apiKey);
        if (isset($response['data'][0]['url'])) {
            $imageUrl = $response['data'][0]['url'];
            $saveTo = './public/img/generated_image' . time() . '.png'; // 保存图像的文件路径
            $this->downloadImage($imageUrl, $saveTo);
        } else {
            echo "Error generating image.";
        }

        return ['text' => $text, 'image' => $saveTo??''];
    }
}
